<?php
/**
 * (logic)
 */
namespace App\Logic\File\ZiNiao;

use App\Models\Basics\SysCountry;
use App\Models\File\FileZiniao;
use App\Util\RExcel;
use Illuminate\Support\Facades\DB;
class ParseFile
{
    /**
     * 解析（紫鸟）
     */
    public static function parse(){
        $parseFiles = FileZiniao::query()->where('status',1)->get();//获取需要解析的数据
        $i = 0;
        $num = 100;
        while(true){
            if($parseFiles->isEmpty())break;
            $_parseFiles = $parseFiles->splice($i,$num);
            try{
                DB::beginTransaction();
                foreach ($_parseFiles as $parseFile){
                    $flag = self::_parseFiles($parseFile);
                    if($flag){
                        $parseFile->status = 2;
                        $parseFile->save();
                        DB::commit();
                    }else{
                        DB::rollBack();
                    }
                }
                sleep(60);
            }catch (\Exception $e){
                DB::rollBack();
                report($e);
            }
        }
    }

    /**
     * 解析文件（紫鸟）
     * @param $parseFile
     * @return bool
     */
    private static function _parseFiles($parseFile){
        $file = self::_getParseFilePath($parseFile);
        if(!is_file($file))return false;
        if(array_key_exists($parseFile->file_type,self::$_class)){
            $lines = RExcel::importSheet($file);
            $flag = (self::$_class[$parseFile->file_type])::exeParse($lines,$parseFile->file_date,$parseFile->country_id);
        }elseif(array_key_exists($parseFile->file_type,self::$_classVB)){
            $lines = RExcel::importSheet($file);
            $flag = (self::$_classVB[$parseFile->file_type])::exeParse($parseFile->id,$lines,$parseFile->file_date,$parseFile->country_id);
        }else{
            $countryId = SysCountry::getIdByCountry('JP');
            $isJP = $countryId == $parseFile->country_id ? true : false;
            $lines = RExcel::importCsvFile($file,$isJP);
            $flag = ParseBusiness::exeParse($lines,$parseFile->file_date,$parseFile->country_id);
        }
        return $flag;
    }

    /**
     * 获取文件路径（紫鸟）
     * @param $parseFile
     * @return string
     */
    private static function _getParseFilePath($parseFile){
        $fileDir = FileOperation::fileDir(strtotime($parseFile->file_date));
        $fileName = FileOperation::fileName($parseFile->country_id,$parseFile->file_type,$parseFile->user_id,$parseFile->file_name);
        return public_uploads_path($fileDir).DIRECTORY_SEPARATOR.$fileName;
    }

    private static $_classVB = [
        3 => ParseVideoCampaign::class,
        4 => ParseBrandsCampaign::class,
    ];

    private static $_class = [
        1 => ParseAds::class,
        5 => ParseDSP::class,
    ];

}
